import { defineComponent, ref, onMounted } from 'vue'
import {ElMessageBox, ElNotification} from "element-plus";
import service from '@/utils/request.js'
import { useStore } from 'vuex'
import { useI18n } from 'vue-i18n'
import Auth from "@/components/mixin/auth";
import useUserStore from '@/store/modules/user'
export default defineComponent({
  name: "RoleManage",
  mixins: [Auth],
  setup() {

    const dialogTree = ref(null)
    const { t } = useI18n()
    const minLevel = ref(2)
    const user = useUserStore().GetInfo()
    const dialogTitle = ref('new role')
    const dialogFormVisible = ref(false)
    const rules = ref( {
      name: [
        { required: true, message: 'Please enter the role name', trigger: 'blur' },
        { min: 2, max: 20, message: 'Length ranging from 2 to 20 characters', trigger: 'blur' }
      ],
      type: [
        { type: 'number', message: 'Please select permission type', trigger: 'change' }
      ],
      level: [
        { type: 'number', message: 'Please enter the role level', trigger: 'change' }
      ],
      menus: [
        { type: 'array', message: 'Please select menu permissions', trigger: 'blur' }
      ], 
      
      desc: [
        { type: 'string', message: 'Please enter role description', trigger: 'change' }
      ],
    })
    const initForm = {
      name: '',
      level: 0,
      type: 0,
      menus: [],
      desc: '',
    }
    const roleTypes = {
      0: 'Custom',
      1: 'All'
    }
    const assetsType = { 
    }
    const defaultProps = {
      label: 'name',
      children: 'children'
    }
    const formParam = ref(Object.assign({}, initForm))
    const dialogForm = ref(null)
    const listData = ref([])
    const allMenus: any = ref([])
    const showMenus = ref([])
    const allAssets = {
    } 

    const getMenuByIds = (menuIds:any) => {
      let remove = false
      const arr: Array<number> = []
      const recursion = (id, menus:any) => {
        for (const m of menus) {
          if (m.parentId === id) {
            remove = true
            return
          }
          if (m.children && m.children.length) {
            recursion(id, m.children)
          }
        }
      }

      for (const id of menuIds) {
        remove = false
        recursion(id, allMenus.value)
        if (!remove) arr.push(id)
      }
      return arr
    }

    const getOwnData = (hasDatas:any) => {
      const arr = []
      for (const [i, n] of hasDatas) {
        for (const j of Object.values(n)) {
          // @ts-ignore
          arr.push(j.id)
        }
      }

      return arr
    }

    const refreshTable = async () => {
      listData.value = (await service.get('shipping/sysRole')).data
    }

    const addClickEvent = () => {
      // @ts-ignore
      minLevel.value = listData.value.find(n => n.id == user.roleId).level + 1
      dialogTitle.value = 'new role'
      dialogFormVisible.value = true
      Object.assign(formParam.value, initForm)
    }

    let editRowId
    const editClickEvent = (row:any) => {
      // @ts-ignore
      minLevel.value = listData.value.find(n => n.id == user.roleId).level + 1
      editRowId = row.id
      dialogTitle.value = 'update role'
      dialogFormVisible.value = true
      Object.keys(formParam.value).forEach(k => row[k] != null && (formParam.value[k] = row[k]))
      // @ts-ignore
      formParam.value.menus = row.type === 1 ? [] : getMenuByIds(row.menus) 
    }

    const removeClickEvent = async (roleId) => {
      await service.delete(`shipping/sysRole/${roleId}`)
      ElMessageBox.confirm('Are you sure to delete the role?', 'Confirmation Information', {type: 'warning', confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",}).then(()=> {
        // @ts-ignore
        ElNotification.success({ title: 'Prompt information', message: 'Successfully deleted role', position: 'bottom-right' })
      })
      refreshTable()
    }

    const submitForm = () => {
      // @ts-ignore
      dialogForm.value.validate(async (flag) => {
        if (!flag) {
          // @ts-ignore
          ElNotification.warning({ title: 'Prompt information', message: 'Verification failed!', position: 'bottom-right' })
          return
        }
        const isAdd = dialogTitle.value === 'new role'
        const params = JSON.parse(JSON.stringify(formParam.value))
        // @ts-ignore
        const tree: any = dialogTree.value
        params.menus = formParam.value.type == 1 ?
          [] : tree.getCheckedKeys().concat(tree.getHalfCheckedKeys())
        await service[isAdd? 'post': 'put'](isAdd ? 'shipping/sysRole' : `shipping/sysRole/${editRowId}`, params)
        // @ts-ignore
        ElNotification.success({ title: 'Prompt information', message: 'Successfully saved', position: 'bottom-right' })
        dialogFormVisible.value = false
        refreshTable()
      })
    }

    const getI18nMenus = (nodes:any, disabled=false) => {
      for (const n of nodes) {
        n.disabled = disabled
        n.name = t(`ship.${n.type == 2 ? 'button': 'route'}.${n.name}`)
        //if (n.name == '系统管理') n.disabled = true
        if (n.children) getI18nMenus(n.children, n.disabled)
      }
    }

    const getDisabledMenus = (nodes:any) => {
      for (const n of nodes) {
        if (n.children) getDisabledMenus(n.children)
        n.disabled = true
      }
    }

 

    onMounted(async () => { 
      allMenus.value = (await service.get('shipping/sysMenu')).data
      getI18nMenus(allMenus.value)
      showMenus.value = JSON.parse(JSON.stringify(allMenus.value))
      getDisabledMenus(showMenus.value)
      refreshTable()
    })


    return {
      allMenus,
      minLevel,
      rules,
      listData,
      formParam,
      assetsType,
      submitForm,
      showMenus,
      getMenuByIds,
      getOwnData,
      allAssets,
      roleTypes,
      dialogForm,
      dialogTitle,
      // checkChange,
      dialogTree,
      defaultProps,
      addClickEvent,
      editClickEvent,
      removeClickEvent,
      dialogFormVisible 
    }
  }
})
